package flex.cc.e2.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import flex.cc.PublicUtil;
import flex.cc.core.utils.RequestUtil;
import flex.cc.e2.service.E2LoginService;
import flex.cc.e2.util.HttpUtil;
import flex.cc.e2.vo.E2ResVo;
import flex.cc.uac.dao.UacUserDao;
import flex.cc.uac.entity.UacUserEntity;
import flex.cc.uac.service.UacUserService;
import lombok.extern.slf4j.Slf4j;

/**
 * 与E2相关的操作
 */
@Service("E2LoginService")
@Slf4j
public class E2LoginServiceImpl implements E2LoginService {

	@Autowired
    private UacUserService uacUserService;
	
	@Autowired
    private UacUserDao uacUserDao;
	
	/**
	 * e2Api接口地址
	 */
	@Value("${e2.e2ApiUrl}")
	private String httpUrl;
	
	/**
	 * e2对接前分配好的key值，验签时使用
	 */
	@Value("${e2.e2clientSecret}")
	private String e2clientSecret;
	
	/**
	 * e2对接前分配好的请求id
	 */
	@Value("${e2.e2clientid}")
	private String e2clientid;
	
    /**
	 * 从E2获取用户登录信息
	 * @param request
	 * @return
	 */
    @Override
    public String cacheUserInfoFromE2(HttpServletRequest request) {
    	try {
    		String e2e = "";
			String e2mf = "";
			// cookies = "e2e=685650C912BE70E7A107B9FDCC9BFEEE; e2mf=ff76898e94f9431c9ad5a6554cb0c935; U2AT=91c4ea90-e5ea-4eb9-a413-c51035c6d72a"
			String cookies = request.getHeader("Cookie");
			System.out.println(cookies);
			if(cookies.indexOf("e2e") == -1 && cookies.indexOf("e2mf") == -1) {
				log.error("未取得E2的kookie，cookies=" + cookies);
	    		return "login";
			} else {
				e2e = cookies.substring(cookies.indexOf("e2e") + 4, cookies.indexOf(";", cookies.indexOf("e2e")));
				e2mf = cookies.substring(cookies.indexOf("e2mf") + 5, cookies.indexOf(";", cookies.indexOf("e2mf")));
			}
			
			String ip = RequestUtil.getRemoteAddr(request);
			String userAgent = request.getHeader("User-Agent");
			Date date = new Date(System.currentTimeMillis());
			String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			time = time.replace(" ", "T");
			System.out.println(time);
			
			Map<String, String> reqForm = new HashMap<String, String>();
			reqForm.put("ip", ip);
			reqForm.put("userAgent", userAgent);
			reqForm.put("e2e", e2e); // token
			reqForm.put("e2mf", e2mf);
			reqForm.put("e2clientid", e2clientid);
			reqForm.put("time", time);
			reqForm.put("sign", getSign(reqForm));
			// 调用E2接口获取登录人信息
			String resJson = HttpUtil.doPostForm(httpUrl, reqForm);
			// 返回：{"status":1,"data":{"email":"t_t1@xdf.cn","e2uid":"d846d3ab-7317-4baf-b8d1-ad050131bae7","u2uid":"d846d3ab-7317-4baf-b8d1-ad050131bae7","nickName":"t_t1","expireTime":"2021-08-10T13:17:43"},"msg":"ok"}
			System.out.println("返回：" + resJson);
			log.info("调用E2接口返回报文=" + resJson + "， e2mf=" + e2mf);
			// 读取登录人邮箱
			String email = "";
			if(!PublicUtil.isEmpty(resJson)) {
				E2ResVo resVo = JSON.parseObject(resJson, new TypeReference<E2ResVo>() {});
				if(!PublicUtil.isEmpty(resVo)) {
					if(resVo.getStatus() == 1) {
						email = resVo.getData().getEmail();
					} else {
						log.error("调用E2接口返回登录已过期，e2mf=" + e2mf);
			    		return "login";
					}
				} else {
					log.error("调用E2接口返回报文解析失败，e2mf=" + e2mf);
		    		return "调用E2接口返回报文解析失败，e2mf=" + e2mf;
				}
			} else {
				log.error("调用E2接口返回报文为空，e2mf=" + e2mf);
	    		return "调用E2接口返回报文为空，e2mf=" + e2mf;
			}
	    	
			// 根据登录人邮箱创建本地缓存
	    	String setMsg = this.setE2TokenToLocal(email, e2mf, request);
	    	
	    	return setMsg;
    	} catch(Exception e) {
    		e.printStackTrace();
    		log.error("将E2信息缓存到本地时出现异常", e);
    		return "将E2信息缓存到本地时出现异常";
    	}
    }
    
    public static void main(String[] args) {
		String resJson = "{\"status\":1,\"data\":{\"email\":\"t_t1@xdf.cn\",\"e2uid\":\"d846d3ab-7317-4baf-b8d1-ad050131bae7\",\"u2uid\":\"d846d3ab-7317-4baf-b8d1-ad050131bae7\",\"nickName\":\"t_t1\",\"expireTime\":\"2021-08-10T13:17:43\"},\"msg\":\"ok\"}";
		E2ResVo resVo = JSON.parseObject(resJson, new TypeReference<E2ResVo>() {});
		System.out.println(resVo);
		
		String cookies = "e2e=685650C912BE70E7A107B9FDCC9BFEEE; e2mf=ff76898e94f9431c9ad5a6554cb0c935; U2AT=91c4ea90-e5ea-4eb9-a413-c51035c6d72a";
		System.out.println(cookies.substring(cookies.indexOf("e2e") + 4, cookies.indexOf(";", cookies.indexOf("e2e"))));
		System.out.println(cookies.substring(cookies.indexOf("e2mf") + 5, cookies.indexOf(";", cookies.indexOf("e2mf"))));
    }
    
    /**
     * 生成校验码
     * @param e2e
     * @param e2mf
     * @param ip
     * @param e2clientid
     * @param time
     * @return
     */
    public String getSign(Map reqForm) {
    	String e2e = reqForm.get("e2e").toString();
    	String e2mf = reqForm.get("e2mf").toString();
    	String ip = reqForm.get("ip").toString();
    	String time = reqForm.get("time").toString();
		String signText = ("VerifyE2MF" + e2e + e2mf + ip + e2clientid + time + e2clientSecret).toLowerCase();
		System.out.println(signText);
		String sign = DigestUtils.md5DigestAsHex(signText.getBytes()).toUpperCase();
		System.out.println(sign);
		return sign;
	}

    /**
     * 对于已经在E2登录的用户，将用户信息存入本地
     * @param userCode
     * @param token
     * @param request
     * @return
     */
	public String setE2TokenToLocal(String email, String token, HttpServletRequest request){
		System.out.println("用户" + email + "已在E2登录，取出登录用户信息，缓存到本地");
		List<UacUserEntity> userList = uacUserDao.selectUserInfoByEmail(email);
		if(!PublicUtil.isEmpty(userList)) {
			UacUserEntity uacUserEntity = userList.get(0);
			uacUserEntity = uacUserDao.selectUserInfoByUserId(uacUserEntity.getId());
			Map<String,String> data = new HashMap<>();
			data.put("token", token);
			data.put("userId", uacUserEntity.getId()+"");
			data.put("userCode",uacUserEntity.getUserCode());
			data.put("userName",uacUserEntity.getUserName());
			data.put("belongComCode",uacUserEntity.getBelongComCode());
			data.put("belongComName",uacUserEntity.getBelongComName());
			data.put("comCode",uacUserEntity.getBelongComCode());
			data.put("comName", uacUserEntity.getBelongComName());
			uacUserService.handlerLoginData(token,data,request);
			log.info("用户" + email + "登录成功");
			return "ok";
		}else {
			log.error("用户" + email + "没有报表系统的操作权限，e2mf=" + token);
			return "用户" + email + "没有报表系统的操作权限，e2mf=" + token;
		}
	}
    
}